﻿@using Abp.Application.Services.Dto;
@using FwProject.Restaurant.Dto
@using FwProject.TypeNumber.Dto
@{
    ViewBag.Title = "加单/补录";
}
@section styles{
    <link href="~/Theme/css/plugins/iCheck/custom.css" rel="stylesheet">
    <link href="~/Theme/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
    <style type="text/css">
        .input-group[class*=col-] {
            padding: 0 15px;
        }
    </style>
}
<div class="row wrapper wrapper-content animated fadeInRight">
    <div class="col-sm-12">
        <div class="ibox float-e-margins">
            <div class="ibox-title">
                <h5>@ViewBag.Title</h5>
                <div class="ibox-tools">

                </div>
            </div>
            <div class="ibox-content" style="height:700px">
                <div class="row m-b-sm m-t-sm">
                    <form class="form-horizontal" id="form" asp-controller="Distribution" asp-action="AddDistribution" data-ajax="true" data-ajax-update="#data_list" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="ReloadAjaxCallbackgoback" data-ajax-failure="FailureAjaxCallback">
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">单号：</label>
                                <div class="input-group">
                                    <input type="text" name="" class="input-sm form-control" value="系统自动生成" readonly="readonly">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">配送日期：</label>
                                <div class="input-group">
                                    <input type="text" name="CreationTime" id="CreationTime" class="input-sm form-control" value="@DateTime.Now.ToString("yyyy-MM-dd")"  autocomplete="off">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">配送司机：</label>
                                <div class="input-group" style="width:162px">
                                    <input type="hidden" name="DriverId" id="DriverId" />
                                    <input type="text" id="dropdown-driverid" class="form-control" onblur="blurEmpty1()" placeholder="全部" style="width:162px">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown" style="line-height:1.455;padding:6px 12px;">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu" style="z-index: 9999;"></ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">餐厅：</label>
                                <div class="input-group" style="width:162px">
                                    <input type="hidden" name="RestaurantId" id="RestaurantId" />
                                    <input type="text" id="dropdown-restaurantid" class="form-control" onblur="blurEmpty()" placeholder="全部" style="width:162px">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown" style="line-height:1.455;padding:6px 12px;">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu" style="z-index: 9999;"></ul>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">店存（应存）：</label>
                                <div class="input-group">
                                    <input type="text" name="DistributionStock" id="StockCount" class="input-sm form-control" value="0" readonly="readonly">

                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">店存（实存）：</label>
                                <div class="input-group">
                                    <input type="text" name="Stock" id="ActualCount" class="input-sm form-control" value="0">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">整单金额：</label>
                                <div class="input-group">
                                    <input type="text" name="Price" id="ZPrice" class="input-sm form-control" value="0" readonly="readonly">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">应收金额：</label>
                                <div class="input-group">
                                    <input type="text" name="TotalPrice" id="TotalPrice" class="input-sm form-control" value="0" readonly="readonly">
                                </div>
                            </div>
                        </div><hr />
                        <div id="data_list">
                            <table class="table table-bordered table-hover table-rowselected" id="tab">
                                <thead>
                                    <tr>
                                        <th width="60px">操作</th>
                                        <th>货品型号</th>
                                        <th>配送箱数</th>
                                        <th>回收箱数</th>
                                        <th>赠送箱数</th>
                                        <th>换货箱数</th>
                                        <th>单价[￥]</th>
                                        <th>金额[￥]</th>
                                        <th>折损套数</th>
                                        <th>折损金额[￥]</th>
                                        <th>退回箱数</th>
                                        <th>退回套数</th>
                                        <th>退回金额[￥]</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div><br />
                        <div class="ibox-tools">
                            <button type="button" class="btn btn-primary btn btn-sm" data-toggle="modal" data-target="#modal_ajax" data-url="@Url.Action("MoreTypeNumber","TypeNumber")" data-backdrop="static">添加货品型号</button>
                            @if (IsGranted(FwProject.Authorization.PermissionNames.Distribution_Operation_Supplement))
                            {
                                <button type="button" class="btn btn-primary btn btn-sm" id="btnSubmit">提交</button>
                            }
                            else
                            {
                                <button type="button" class="btn btn-default btn btn-sm">无加单补录权限</button>
                            }
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>
</div>
<div id="modal_ajax" class="modal inmodal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
</div>

@section scripts{
    <script src="~/Theme/js/content.min.js?v=1.0.0"></script>
    <script src="~/Theme/js/plugins/iCheck/icheck.min.js"></script>
    <script src="~/Theme/js/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script src="~/Theme/js/plugins/suggest/bootstrap-suggest2014.js"></script>
    <script src="~/js/DateComm.js"></script>
    <script>
        var StockCount = 0;
        var ActualCount = 0;
        $(document).ready(function () {
            $.getJSON("/Users/GetSuggestData?type=司机类型").done(function (data) {
                CommonAjaxCallback(data, function () {
                    bindSuggest1(data.result);
                }, null);
            }).fail(function () {
                layer.msg('连接超时，获取司机信息失败！', {
                    icon: 2,
                    time: 2000
                });
                });


            $('#CreationTime').datepicker({
                todayBtn: "linked",
                autoclose: true,
                todayHighlight: true,
                endDate: new Date()

            });

        })

        $("#btnSubmit").click(function () {
            layer.confirm('是否确认提交?', { icon: 3, title: '提示' }, function (index) {
                $('#form').submit();
                layer.close(index);
            });

        });

        function bindSuggest(data) {
            if ($("#dropdown-restaurantid") != undefined) {
                $role = $("#dropdown-restaurantid").bsSuggest({
                    effectiveFields: ["restaurantName"],
                    effectiveFieldsAlias: { "restaurantName": "餐厅名称" },
                    searchFields: ["restaurantName"],
                    clearable: true,
                    getDataMethod: "data",
                    //url: "/Users/GetSuggestData?type=司机类型&keyword=",
                    data: { value: data },
                    idField: "id",
                    keyField: "restaurantName",
                    emptyTipL: "无餐厅信息，请先选择配送司机",
                    callfun: function () {
                        $("#RestaurantId").val("");
                    }
                }).on('onDataRequestSuccess', function (e, result) {
                    console.log('onDataRequestSuccess: ', result);
                }).on('onSetSelectValue', function (e, keyword, data) {
                    $.post("/Restaurant/GetRestaurantTypeNumberCount", { "Id": "" + data.id + "" }, function (e) {
                        $('#StockCount').val(e.result);
                        $('#ActualCount').val(e.result);
                        ActualCount = StockCount = e.result;
                    });
                    var id = data.id;
                    var tbody = $('#tab').find('tbody');
                    LoadTypeNumber(tbody, id);
                    $("#RestaurantId").val(data.id);
                    console.log('onSetSelectValue: ', keyword, data);
                }).on('onUnsetSelectValue', function () {
                    console.log('onUnsetSelectValue');
                });
            }
        }
        function blurEmpty() {
            var cityObj = $("#dropdown-restaurantid");
            var DriverId = $("#RestaurantId");
            if (cityObj.val() == "") {
                DriverId.attr("value", "");
            }
        }
        function bindSuggest1(data) {
            if ($("#dropdown-driverid") != undefined) {
                $role = $("#dropdown-driverid").bsSuggest({
                    effectiveFields: ["name"],
                    effectiveFieldsAlias: { "name": "姓名" },
                    searchFields: ["name"],
                    clearable: true,
                    getDataMethod: "data",
                    //url: "/Users/GetSuggestData?type=司机类型&keyword=",
                    data: { value: data },
                    idField: "id",
                    keyField: "name",
                    callfun: function () {
                        $("#DriverId").val("");
                    }
                }).on('onDataRequestSuccess', function (e, result) {
                    console.log('onDataRequestSuccess: ', result);
                }).on('onSetSelectValue', function (e, keyword, data) {
                    $("#dropdown-restaurantid").bsSuggest("destroy");
                    $.getJSON("/Distribution/GetRestaurantData?driverId=" + data.id).done(function (data) {
                        CommonAjaxCallback(data, function () {
                            bindSuggest(data.result);
                        }, null);
                    }).fail(function () {
                        layer.msg('连接超时，获取司机信息失败！', {
                            icon: 2,
                            time: 2000
                        });
                    });
                    $("#DriverId").val(data.id);
                    console.log('onSetSelectValue: ', keyword, data);
                }).on('onUnsetSelectValue', function () {
                    console.log('onUnsetSelectValue');
                });
            }
        }
        function blurEmpty1() {
            var cityObj = $("#dropdown-driverid");
            var DriverId = $("#DriverId");
            if (cityObj.val() == "") {
                DriverId.attr("value", "");
            }
        }


        function LoadTypeNumber(tbody, id) {
            tbody.empty();
            $(tbody).load("/RestaurantTypeNumber/GetTypeNumbersView?id=" + id, function () {
                layer.msg('加载完成！', {
                    icon: 1,
                    time: 2000
                });
            });
        }
        ///监听选中情况

        $('#modal_ajax').on("click", "#allchecked", function () {
            if (this.checked) {
                $("input[name='typeNumberIds']:checkbox").each(function () {
                    $(this).attr("checked", true);
                });
            } else {
                $("input[name='typeNumberIds']:checkbox").each(function () {
                    $(this).attr("checked", false);
                });
            }
        });

        $('#modal_ajax').on("click", "#enterTypeNumber", function () {

            var ids = []
            $("input[name='typeNumberIds']:checked").each(function () {
                ids.push({ "Id": $(this).data("id"), "Count": $(this).data("count"), "Name": $(this).data("name") });
            });
            var tbody = $('#tab').find('tbody');
            var id = $("#RestaurantId").val();
            if (id == "") {
                layer.msg('请选择餐厅！', {
                    icon: 1,
                    time: 2000
                });
                return;
            }
            $.post("/TypeNumber/GetTypeNumbersView", { "typeNumberInfoDtos": ids, "id": id, "trlength": $(tbody).find("tr").length }, function (data) {
                $(data).appendTo("#tab");
                layer.msg('加载完成！', {
                    icon: 1,
                    time: 2000
                });
            });
        });



        ///添加其他型号
        $('#modal_ajax').on('show.bs.modal', function (e) {
            $(this).addClass('loading');
            var $button = $(e.relatedTarget);
            var url = $button.data('url');
            if (!!url) {
                url = url + ((url.indexOf("?") > -1) ? "&r=" : "?r=") + Math.random();
                $(this).load(url, function () {
                    $.validator.unobtrusive.parse(this); //$("#form_model_create").validate();
                    $(this).removeClass('loading');
                });
            }
        });

        $('#modal_ajax').on('hidden.bs.modal', function (e) {
            $(this).empty();
        });




        ///删除当前行
        function removertr(obj) {
            $(obj).parent().remove();
        }

        function setPrice(obj) {
            var tr = $(obj).parent().parent();
            var Distributioncount = parseInt($(tr).find("td input").eq(5).val());
            var Recoverycount = parseInt($(tr).find("td input").eq(6).val());
            var Givecount = parseInt($(tr).find("td input").eq(7).val());
            var Exchangegoodscount = parseInt($(tr).find("td input").eq(8).val());
            var Damagecount = parseInt($(tr).find("td input").eq(11).val());
            var Backboxcount = parseInt($(tr).find("td input").eq(13).val());
            var Backnumbercount = parseInt($(tr).find("td input").eq(14).val());

            if (Distributioncount < 0) {
                $(tr).find("td input").eq(5).val(0);
                Distributioncount = 0;
            }
            if (Recoverycount < 0) {
                $(tr).find("td input").eq(6).val(0);
                Recoverycount = 0;
            }
            if (Givecount < 0) {
                $(tr).find("td input").eq(7).val(0);
                Givecount = 0;
            }
            if (Exchangegoodscount < 0) {
                $(tr).find("td input").eq(8).val(0);
                Exchangegoodscount = 0;
            }
            if (Damagecount < 0) {
                $(tr).find("td input").eq(11).val(0);
                Damagecount = 0;
            }
            if (Backboxcount < 0) {
                $(tr).find("td input").eq(13).val(0);
                Backboxcount = 0;
            }
            if (Backnumbercount < 0) {
                $(tr).find("td input").eq(14).val(0);
                Backnumbercount = 0;
            }
            var Count = parseInt($(tr).find("td input").eq(4).val());
            var Price = $(tr).find("td input").eq(9).val();
            $(tr).find("td input").eq(10).val(toFloat(Distributioncount * Count * Price));
            $(tr).find("td input").eq(12).val(toFloat(Damagecount * Price));
            //$(tr).find("td input").eq(14).val(Backboxcount * Count);
            $(tr).find("td input").eq(15).val(toFloat(Backboxcount * Count * Price+ Backnumbercount * Price));

            var trCount = $("#tab tbody tr");
            if (trCount.length > 0) {
                var sumPrice = 0;
                var SumDistrinbutioncount = 0;
                var SumGiveCount = 0;
                var SumRecoverycount = 0;
                var SumBackboxcount = 0;
                for (var i = 0; i < trCount.length; i++) {
                    var price = $(trCount[i]).find("td input").eq(9).val();
                    sumPrice += ($(trCount[i]).find("td input").eq(5).val() * $(trCount[i]).find("td input").eq(4).val() * price - ($(trCount[i]).find("td input").eq(11).val() * price)) - ($(trCount[i]).find("td input").eq(13).val() * Count* price)- ($(trCount[i]).find("td input").eq(14).val() * price);
                    SumDistrinbutioncount += parseInt($(trCount[i]).find("td input").eq(5).val());
                    SumGiveCount += parseInt($(trCount[i]).find("td input").eq(7).val());
                    SumRecoverycount += parseInt($(trCount[i]).find("td input").eq(6).val());
                    SumBackboxcount += parseInt($(trCount[i]).find("td input").eq(13).val());
                }
                $('#ZPrice').val(toFloat(sumPrice));
                $('#TotalPrice').val(toFloat(sumPrice));

                $('#StockCount').val(parseInt(StockCount) + SumDistrinbutioncount + SumGiveCount - SumRecoverycount - SumBackboxcount);
                $('#ActualCount').val(parseInt(ActualCount) + SumDistrinbutioncount + SumGiveCount - SumRecoverycount - SumBackboxcount);
            }
        }

        function ReloadAjaxCallbackgoback(data, successInfo) {
            CommonAjaxCallback(data, function () {
                window.location.reload();
            }, successInfo);
        }

        var toFloat = function (value) {
            value = Math.round(parseFloat(value) * 100) / 100;
            if (value.toString().indexOf(".") < 0) {
                value = value.toString() + ".00";
            }
            return value;
        }
    </script>
}